package com.youi.webapp;

import com.alibaba.fastjson.JSONObject;
import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.entity.Groupleader;
import com.youi.entity.Leaderfan;
import com.youi.entity.Leaderprofit;
import com.youi.entity.Leaderprofitdetail;
import com.youi.entity.Leaderstore;
import com.youi.entity.Merchant;
import com.youi.entity.Ordergoods;
import com.youi.entity.Orderprofitdetail;
import com.youi.entity.Purchasehistory;
import com.youi.entity.Refundorder;
import com.youi.entity.User;
import com.youi.entity.Userorder;
import com.youi.entity.Userwechat;
import com.youi.entity.Yibaopayment;
import com.youi.entity.Yibaorefund;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.service.GroupleaderService;
import com.youi.service.LeaderfanService;
import com.youi.service.LeaderprofitService;
import com.youi.service.LeaderprofitdetailService;
import com.youi.service.LeaderstoreService;
import com.youi.service.MerchantService;
import com.youi.service.OrdergoodsService;
import com.youi.service.OrderprofitdetailService;
import com.youi.service.PurchasehistoryService;
import com.youi.service.RefundorderService;
import com.youi.service.SetleaderlevelService;
import com.youi.service.UserService;
import com.youi.service.UserorderService;
import com.youi.service.UserwechatService;
import com.youi.service.YibaopaymentService;
import com.youi.service.YibaorefundService;
import com.youi.third.yibaopay.YibaopayUtil;
import com.youi.util.CommonInfoUtil;
import com.youi.util.IpUtil;
import com.youi.util.JsonUtil;
import com.youi.util.LogUtil;
import com.youi.util.ObjectUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;

@Controller
public class UserPayController extends HttpRequestManage implements ApplicationContextAware {

    @Autowired
    private OrdergoodsService ordergoodsService;
    @Autowired
    private UserorderService userorderService;
    @Autowired
    private UserwechatService userwechatService;
    @Autowired
    private UserService userService;
    @Autowired
    private LeaderfanService leaderfanService;
    @Autowired
    private YibaopaymentService yibaopaymentService;
    @Autowired
    private LeaderprofitService leaderprofitService;
    @Autowired
    private SetleaderlevelService setleaderlevelService;
    @Autowired
    private GroupleaderService groupleaderService;
    @Autowired
    private LeaderprofitdetailService leaderprofitdetailService;
    @Autowired
    private OrderprofitdetailService orderprofitdetailService;
    @Autowired
    private LeaderstoreService leaderstoreService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private PurchasehistoryService purchasehistoryService;
    @Autowired
    private YibaorefundService yibaorefundService;
    @Autowired
    private RefundorderService refundorderService;

    //微信支付
    private static Integer WAPWECHPAY = 2;
    //未支付状态
    private static Integer NOPAY = 0;
    //支付成功状态
    private static Integer SUCESS = 4;
    //取消状态
    private static Integer CANCEL = -3;
    //已支付待发货
    private static Integer PAID = 1;
    //订单已关闭
    private static Integer CLOSE = -1;

    /**
     * 同步静态对象 零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码：生成零长度的byte[]对象只需3条操作码，而Object lock = new Object()则需要7行操作码
     */
    private static byte[] lock = null;

    /**
     * M-21
     * 订单调用易宝支付返回json串(购物车和马上抢专用)
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("userGetInfo/yibaoPayOrder")
    public String yibaoPayOrder(ModelMap modelMap, HttpServletRequest request) throws BusinessException, IOException {
        User user = (User) HttpSessionManage.getAttribute(request, SessionKey.USER);
        String serialNumber = getString("orderId", request);
        String requestIp = IpUtil.getIpAddr(request);

        Yibaopayment yibaopayment = yibaopaymentService.payBySerialNumber(serialNumber, user, requestIp);

        modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
        modelMap.put(CommonInfoUtil.JSONMSG, "操作成功");
        modelMap.put(CommonInfoUtil.DATA, JSONObject.parseObject(yibaopayment.getPayData()));
        modelMap.put("uniqueOrderNo", yibaopayment.getPaymentNo());
        modelMap.put("orderNo", serialNumber);
        return JsonUtil.toJson(modelMap);
    }

    /**
     * 订单调用易宝支付返回json串(待支付订单专用)
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("userGetInfo/yibaoPayOrderByUnpaid")
    public String yibaoPayOrderByUnpaid(ModelMap modelMap, HttpServletRequest request) throws BusinessException, IOException {
        User user = (User) HttpSessionManage.getAttribute(request, SessionKey.USER);
        Long orderId = getLong("orderId", request);
        String requestIp = IpUtil.getIpAddr(request);

        Yibaopayment yibaopayment = yibaopaymentService.payByOrderId(orderId, user, requestIp);

        modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
        modelMap.put(CommonInfoUtil.JSONMSG, "操作成功");
        modelMap.put(CommonInfoUtil.DATA, JSONObject.parseObject(yibaopayment.getPayData()));
        modelMap.put("uniqueOrderNo", yibaopayment.getPaymentNo());
        modelMap.put("orderNo", yibaopayment.getSerialNumber());
        return JsonUtil.toJson(modelMap);
    }


    /**
     * 易宝支付--小程序回调
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("yibaopayCallBack")
    public String yibaopayCallBack(ModelMap modelMap, HttpServletRequest request) throws BusinessException, IOException {
        String serialNumber = getString("orderNo", request);
        String uniqueOrderNo = getString("uniqueOrderNo", request);
        String paymentResult = getString("data", request);
        yibaopaymentService.callBackForMiniApp(serialNumber, uniqueOrderNo);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
    }


    /**
     * 易宝支付--易宝付款回调
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @RequestMapping("checkYibaoPaySuccess")
    public String checkYibaoPaySuccess(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        LogUtil.Info("易宝支付回调");
        System.out.println("易宝支付回调");
        String response = getString("response", request);
        String result = YibaopayUtil.callBack(response);
        if (!result.contains("SUCCESS")) {
            LogUtil.Info("===============回调数据" + response);
            modelMap.put(CommonInfoUtil.EXCEPTION, "支付回调异常");
            return JsonUtil.toJson(modelMap);
        }
        JSONObject data = JSONObject.parseObject(result);
        if (data != null && data.get("status").equals("SUCCESS")) {
            DecimalFormat amount = new DecimalFormat("0.00");
            Map<String, Object> prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("serialNumber", data.get("orderId"));
            Yibaopayment yibaopayment = yibaopaymentService.getByParam(prams);
            if (yibaopayment != null) {
                prams = new HashMap<String, Object>();
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put("orderNo", ObjectUtil.getStrListByIds(yibaopayment.getOrderNos()));
                List<Userorder> userorderList = userorderService.getByParams(prams);
                if (userorderList != null && userorderList.size() > 0) {
                    for (Userorder userorder : userorderList) {
                        LogUtil.Info("==================================进行易宝支付回调" + userorder.getOrderNo());
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("orderNo", userorder.getOrderNo());
                        Orderprofitdetail orderprofitdetail = orderprofitdetailService.getByParam(prams);
                        if (orderprofitdetail == null) {
                            userorder.setStatus(PAID);//订单状态
                            userorder.setGmtPay(new Date());
                            userorder.setGmtModify(new Date());
                            prams = new HashMap<String, Object>();
                            prams.put(Common.DELSTATUS, DelStatus.NODEL);
                            prams.put(Common.USERID, userorder.getUserId());
                            Userwechat userwechat = userwechatService.getByParam(prams);
                            Merchant merchant = merchantService.get(userorder.getMerchantId());
                            User user = userService.get(userorder.getUserId());
                            getLoginMsg(user);
                            checkFans(userorder.getUnioid(), userorder, user);
                            getLeaderprofit(userorder, userorder.getPayableAmount(), user, merchant, userwechat);
                            userorderService.saveOrUpdate(userorder);
                            addBuyHistory(user, userorder);
                            LogUtil.Info("==========================支付成订状态改为待发货");
                        }
                    }
                }
            }
        }
        return "SUCCESS";
    }

    /**
     * 易宝退款--易宝退款回调
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("checkYibaoRefundSuccess")
    public String checkYibaoRefundSuccess(ModelMap modelMap, HttpServletRequest request) throws BusinessException, IOException {
        LogUtil.Info("易宝退款回调");
        System.out.println("易宝退款回调");
        String response = getString("response", request);
        String result = YibaopayUtil.callBack(response);
        if (!result.contains("SUCCESS")) {
            LogUtil.Info("===============回调数据" + response);
            modelMap.put(CommonInfoUtil.EXCEPTION, "支付回调异常");
            return JsonUtil.toJson(modelMap);
        }
        JSONObject data = JSONObject.parseObject(result);
        if (data != null && data.getString("status").equals("SUCCESS")) {
            LogUtil.Info("=====================发起退款回调" + data);
            Map<String, Object> prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("refundOrderNo", data.getString("refundRequestId"));
            Yibaorefund yibaorefund = yibaorefundService.getByParam(prams);
            if (yibaorefund != null) {
                LogUtil.Info("===================易宝退款订单存在执行退款回调进入下一步");
                prams = new HashMap<String, Object>();
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put("orderNo", yibaorefund.getOrderNo());
                Userorder userorder = userorderService.getByParam(prams);
                LogUtil.Info("=======================订单存在" + userorder);
                if (userorder != null) {
                    if (userorder.getRefund() == 1) {
                        Integer check = null;
                        if (userorder.getStatus() != 5) {
                            check = getLeaderprofitBack(userorder);
                        } else {
                            check = 1;
                        }
                        LogUtil.Info("===================佣金退判定" + check);
                        if (check == 1) {
                            LogUtil.Info("===================易宝退款佣金返回进入下一步");
                            userorder.setRefund(2);
                            userorder.setGmtModify(new Date());
                            userorderService.saveOrUpdate(userorder);
                            yibaorefund.setStatus(data.getString("status"));
                            yibaorefund.setRefundAmount(data.getString("realRefundAmount"));
                            yibaorefundService.saveOrUpdate(yibaorefund);
                            prams = new HashMap<String, Object>();
                            prams.put(Common.DELSTATUS, DelStatus.NODEL);
                            prams.put("orderNo", userorder.getOrderNo());
                            Refundorder refundorder = refundorderService.getByParam(prams);
                            if (refundorder != null) {
                                refundorder.setStatus(1);
                                refundorder.setRefundAmount(Double.valueOf(yibaorefund.getRefundAmount()));
                                refundorderService.saveOrUpdate(refundorder);
                                LogUtil.Info("=========退款回调执行成功===========");
                            }
                        }
                    }
                }
            }
        }
        return "SUCCESS";
    }

    /**
     * 易宝入网--分账方注册回调
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("checkEnterMerchant")
    public String checkEnterMerchant(ModelMap modelMap, HttpServletRequest request) throws BusinessException, IOException {
        LogUtil.Info("分账方注册回调回调");
        String response = getString("response", request);
        LogUtil.Info("======注册回调数据=====" + response);

        String result = YibaopayUtil.callBack(response);
        if (result == null || result.length() == 0) {
            modelMap.put(CommonInfoUtil.EXCEPTION, "支付回调异常");
            return JsonUtil.toJson(modelMap);
        }
        JSONObject data = JSONObject.parseObject(result);
        String merchantNo = data.getString("merNo");
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("merchantNo", merchantNo);
        Merchant merchant = merchantService.getByParam(prams);
        if (merchant == null) {
            LogUtil.Info("注册的商家不存在");
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "商家不存在");
        }
        if (data != null && data.getString("merNetInStatus").equals("PROCESS_SUCCESS")) {
            merchant.setYibaoStatus(2);
            merchantService.saveOrUpdate(merchant);
            LogUtil.Info("===========商家成功入网易宝");
            return "SUCCESS";
        } else if (data != null && data.getString("merNetInStatus").equals("PROCESSING_PRODUCT_INFO_SUCCESS")) {
            return "";
        } else {
            merchant.setYibaoStatus(-1);
            merchant.setYibaoRemark(data.getString("remark"));
            LogUtil.Info("===========商家入网易宝失败");
            merchantService.saveOrUpdate(merchant);
            LogUtil.Info("===========入网易宝操作完成");
            return "SUCCESS";
        }
    }

    /**
     * 验证是否粉丝
     *
     * @param unionid 用户unionid
     */
    public void checkFans(String unionid, Userorder userorder, User user) {
        if (userorder.getLeaderId() != null && userorder.getLeaderId() != 0 && user.getLeaderLevel() == 0) {
            Map<String, Object> prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put(Common.UNIONID, unionid);
            Leaderfan leaderfan = leaderfanService.getByParam(prams);
            if (leaderfan == null) {
                leaderfan = new Leaderfan(userorder.getLeaderId(), unionid);
            } else {
                leaderfan.setOrderCount(leaderfan.getOrderCount() + 1);
                leaderfan.setGmtLatsBuy(new Date());
            }
            leaderfanService.saveOrUpdate(leaderfan);
        }
    }


    /**
     * 团长佣金信息分账
     */
    public void getLeaderprofit(Userorder userorder, Double payAmount, User user, Merchant merchant, Userwechat userwechat) {
        Orderprofitdetail orderprofitdetail = null;
        //商家佣金
        Double merchantComms = ObjectUtil.sciCal(payAmount * (1 - (merchant.getCommissionRatio() * 0.01)), 2);
        //手续费
        Double serviceCharge = ObjectUtil.sciCal(payAmount * 0.003, 2);
        Double platComms = null;
        //判断用户身份
        Integer identity = checkUserIidentity(userorder.getUserId());
        if (identity == 0) {
            //当用户为非粉丝和非团长时
            platComms = ObjectUtil.sciCal(payAmount - merchantComms - serviceCharge, 2);//平台佣金
            orderprofitdetail = new Orderprofitdetail(2, userorder.getOrderNo(), userorder.getPayableAmount());
            orderprofitdetail.setPlatAmount(platComms);
            orderprofitdetail.setMerchantId(userorder.getMerchantId());
            orderprofitdetail.setMerAmount(merchantComms);
            orderprofitdetail.setServiceCharge(serviceCharge);
            orderprofitdetailService.saveOrUpdate(orderprofitdetail);
        } else if (identity == 1) {
            //当用户为粉丝的时候
            getleaderComms(userwechat, orderprofitdetail, userorder, payAmount, merchantComms, serviceCharge, platComms);
        } else if (identity == 2) {
            //当用户为团长的时候
            getLeaderOneselfComms(userwechat, orderprofitdetail, userorder, payAmount, merchantComms, serviceCharge, platComms);
        }
    }

    /**
     * 添加购买记录
     *
     * @param user
     * @param userorder
     */
    public void addBuyHistory(User user, Userorder userorder) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderId", userorder.getId());
        List<Ordergoods> ordergoodsList = ordergoodsService.getByParams(prams);
        if (ordergoodsList != null && ordergoodsList.size() > 0) {
            for (Ordergoods ordergoods : ordergoodsList) {
                purchasehistoryService.saveOrUpdate(new Purchasehistory(user.getId(), ordergoods.getGoodsId(), ordergoods.getCount()));
            }
        }
    }

    private void getLoginMsg(User user) throws BusinessException {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.USERID, user.getId());
        Groupleader groupleader = groupleaderService.getByParam(prams);
        Userwechat userother = userwechatService.getByParam(prams);
        user.setUnionId(userother.getUnionid());
        if (groupleader != null) {
            user.setLeaderId(groupleader.getId());
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("leaderId", groupleader.getId());
            List<Leaderstore> leaderstoreList = leaderstoreService.getByParams(prams);
            for (Leaderstore leaderstore : leaderstoreList) {
                if (leaderstore.getLevel() == 1) {
                    user.setLeaderLevel(1);
                } else if (leaderstore.getLevel() == 2) {
                    user.setLeaderLevel(2);
                }
                break;
            }
        } else {
            user.setLeaderLevel(0);
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        LogUtil.Info("unionid=" + userother.getUnionid());
        prams.put("unionid", userother.getUnionid());
        Leaderfan leaderfan = leaderfanService.getByParam(prams);
        LogUtil.Info("leaderfan=" + leaderfan);
        if (leaderfan == null) {
            LogUtil.Info("验证是否粉丝");
            user.setIsFans(0);
        } else {
            user.setIsFans(1);
        }

    }

    /**
     * 检测订单用户身份
     *
     * @param userId
     * @return 0非粉丝 1粉丝 2团长
     */
    private Integer checkUserIidentity(Long userId) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.USERID, userId);
        Userwechat userother = userwechatService.getByParam(prams);
        if (userother != null) {
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("unionid", userother.getUnionid());
            Leaderfan leaderfan = leaderfanService.getByParam(prams);
            if (leaderfan != null) {
                return 1;
            }
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put(Common.USERID, userId);
            Groupleader groupleader = groupleaderService.getByParam(prams);
            if (groupleader != null) {
                return 2;
            }
        }
        return 0;
    }

    /**
     * 团长佣金计算方法
     *
     * @param userwechat
     * @param orderprofitdetail
     * @param userorder
     * @param payAmount
     * @param merchantComms
     * @param serviceCharge
     * @param platComms
     */
    private void getleaderComms(Userwechat userwechat, Orderprofitdetail orderprofitdetail, Userorder userorder, Double payAmount, Double merchantComms, Double serviceCharge, Double platComms) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("unionid", userwechat.getUnionid());
        Leaderfan leaderfan = leaderfanService.getByParam(prams);
        if (leaderfan != null) {
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put(Common.ID, leaderfan.getLeaderId());
            Groupleader groupleader = groupleaderService.getByParam(prams);
            if (groupleader != null) {
                prams = new HashMap<String, Object>();
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put("leaderId", groupleader.getId());
                Map<String, Object> sortParams = new HashMap<String, Object>();
                sortParams.put(Common.ID, Common.DESC);
                Leaderstore leaderstore = leaderstoreService.getByParam(prams, null, sortParams);
                if (leaderfan != null) {
                    if (leaderstore.getLevel() == 1) {
                        //订单为一级团长订单时
                        //查询团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("leaderId", leaderstore.getLeaderId());
                        Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
                        if (leaderprofit == null) {
                            leaderprofit = new Leaderprofit(userorder.getLeaderId());
                            leaderprofitService.saveOrUpdate(leaderprofit);
                        }
                        //计算团长佣金
                        //1.确定团长佣金比例
                        Double topLeaderRate = ObjectUtil.sciCal(setleaderlevelService.getLeaderRate(1) + setleaderlevelService.getLeaderRate(2), 2);
                        //2.计算团长佣金
                        Double leaderComms = ObjectUtil.sciCal(payAmount * (topLeaderRate * 0.01), 2);
                        //3.计算平台佣金
                        platComms = ObjectUtil.sciCal(payAmount - merchantComms - leaderComms - serviceCharge, 2);
                        //添加团长佣金信息
                        leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() + leaderComms);
                        leaderprofit.setFrozen(leaderprofit.getFrozen() + leaderComms);
                        leaderprofit.setGmtModify(new Date());
                        leaderprofitService.saveOrUpdate(leaderprofit);
                        //添加团长佣金流水
                        leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 0, leaderComms, "佣金收入", userorder.getOrderNo()));
                        //添加分佣记录
                        orderprofitdetail = new Orderprofitdetail(0, userorder.getOrderNo(), userorder.getPayableAmount());
                        orderprofitdetail.setLeaderId1(leaderstore.getLeaderId());
                        if (groupleader != null) {
                            orderprofitdetail.setFirstUser(groupleader.getName());
                        }
                        orderprofitdetail.setFirstAmount(Double.valueOf(leaderComms));
                        orderprofitdetail.setPlatAmount(platComms);
                        orderprofitdetail.setMerchantId(userorder.getMerchantId());
                        orderprofitdetail.setMerAmount(merchantComms);
                        orderprofitdetail.setServiceCharge(serviceCharge);
                        orderprofitdetailService.saveOrUpdate(orderprofitdetail);
                    } else if (leaderstore.getLevel() == 2) {
                        //当团长为二级团长时
                        //1.确定二级团长的佣金
                        Double secondLeaderComms = ObjectUtil.sciCal(payAmount * (setleaderlevelService.getLeaderRate(2) * 0.01), 2);
                        //2.确定一级团长佣金
                        Double firstLeaderComms = ObjectUtil.sciCal(payAmount * (setleaderlevelService.getLeaderRate(1) * 0.01), 2);
                        //3.计算一二级团长佣金的总和
                        Double allLeaderComms = ObjectUtil.sciCal(secondLeaderComms + firstLeaderComms, 2);
                        //4.计算平台佣金
                        platComms = ObjectUtil.sciCal(payAmount - merchantComms - allLeaderComms - serviceCharge, 2);
                        //5.添加二级团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("leaderId", leaderstore.getLeaderId());
                        Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
                        if (leaderprofit == null) {
                            leaderprofit = new Leaderprofit(userorder.getLeaderId());
                            leaderprofitService.saveOrUpdate(leaderprofit);
                        }
                        leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() + secondLeaderComms);
                        leaderprofit.setFrozen(leaderprofit.getFrozen() + secondLeaderComms);
                        leaderprofit.setGmtModify(new Date());
                        leaderprofitService.saveOrUpdate(leaderprofit);
                        //添加二级团长佣金流水
                        leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 0,
                                secondLeaderComms, "佣金收入", userorder.getOrderNo()));
                        //6.添加一级团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("storeId", leaderstore.getStoreId());
                        prams.put("level", 1);
                        Leaderstore topLeaderstore = leaderstoreService.getByParam(prams);
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put(Common.ID, leaderstore.getLeaderId());
                        Groupleader firstGroupleader = groupleaderService.getByParam(prams);
                        if (firstGroupleader != null) {
                            prams = new HashMap<String, Object>();
                            prams.put(Common.DELSTATUS, DelStatus.NODEL);
                            prams.put("leaderId", topLeaderstore.getLeaderId());
                            Leaderprofit topleaderprofit = leaderprofitService.getByParam(prams);
                            if (topleaderprofit == null) {
                                topleaderprofit = new Leaderprofit(topLeaderstore.getLeaderId());
                                leaderprofitService.saveOrUpdate(topleaderprofit);
                            }
                            //添加顶级团长佣金信息
                            topleaderprofit.setTotalAmount(topleaderprofit.getTotalAmount() + firstLeaderComms);
                            topleaderprofit.setFrozen(topleaderprofit.getFrozen() + firstLeaderComms);
                            topleaderprofit.setGmtModify(new Date());
                            leaderprofitService.saveOrUpdate(topleaderprofit);
                            //添加顶级团长佣金流水
                            leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(topLeaderstore.getLeaderId(), 0, firstLeaderComms, "佣金收入", userorder.getOrderNo()));
                            //添加分佣记录
                            orderprofitdetail = new Orderprofitdetail(1, userorder.getOrderNo(), userorder.getPayableAmount());
                            orderprofitdetail.setLeaderId1(topLeaderstore.getLeaderId());
                            if (groupleader != null) {
                                orderprofitdetail.setFirstUser(firstGroupleader.getName());
                            }
                            orderprofitdetail.setFirstAmount(firstLeaderComms);
                            orderprofitdetail.setLeaderId2(leaderstore.getLeaderId());
                            orderprofitdetail.setSecondUser(groupleader.getName());
                            orderprofitdetail.setSecondAmount(secondLeaderComms);
                            orderprofitdetail.setPlatAmount(platComms);
                            orderprofitdetail.setMerchantId(userorder.getMerchantId());
                            orderprofitdetail.setMerAmount(merchantComms);
                            orderprofitdetail.setServiceCharge(serviceCharge);
                            orderprofitdetailService.saveOrUpdate(orderprofitdetail);
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取自己是团长的佣金
     *
     * @param userwechat
     * @param orderprofitdetail
     * @param userorder
     * @param payAmount
     * @param merchantComms
     * @param serviceCharge
     * @param platComms
     */
    private void getLeaderOneselfComms(Userwechat userwechat, Orderprofitdetail orderprofitdetail, Userorder userorder, Double payAmount, Double merchantComms, Double serviceCharge, Double platComms) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.USERID, userorder.getUserId());
        Groupleader groupleader = groupleaderService.getByParam(prams);
        //查询下单人团长信息
        if (groupleader != null) {
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("leaderId", groupleader.getId());
            Map<String, Object> sortParams = new HashMap<String, Object>();
            sortParams.put(Common.ID, Common.DESC);
            Leaderstore leaderstore = leaderstoreService.getByParam(prams, null, sortParams);
            if (leaderstore != null) {
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put("leaderId", leaderstore.getLeaderId());
                Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
                if (leaderprofit == null) {
                    leaderprofit = new Leaderprofit(leaderstore.getLeaderId());
                    leaderprofitService.saveOrUpdate(leaderprofit);
                }
                if (leaderstore.getLevel() == 1) {
                    //订单为一级团长订单时
                    //计算团长佣金
                    //1.确定团长佣金比例
                    Double topLeaderRate = ObjectUtil.sciCal(setleaderlevelService.getLeaderRate(1) + setleaderlevelService.getLeaderRate(2), 2);
                    //2.计算团长佣金
                    Double leaderComms = ObjectUtil.sciCal(payAmount * (topLeaderRate * 0.01), 2);
                    //3.计算平台佣金
                    platComms = ObjectUtil.sciCal(payAmount - merchantComms - leaderComms - serviceCharge, 2);
                    //添加团长佣金信息
                    leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() + leaderComms);
                    leaderprofit.setFrozen(leaderprofit.getFrozen() + leaderComms);
                    leaderprofit.setGmtModify(new Date());
                    leaderprofitService.saveOrUpdate(leaderprofit);
                    //添加团长佣金流水
                    leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 0, leaderComms, "佣金收入", userorder.getOrderNo()));
                    //添加分佣记录
                    orderprofitdetail = new Orderprofitdetail(0, userorder.getOrderNo(), userorder.getPayableAmount());
                    orderprofitdetail.setLeaderId1(leaderstore.getLeaderId());
                    if (groupleader != null) {
                        orderprofitdetail.setFirstUser(groupleader.getName());
                    }
                    orderprofitdetail.setFirstAmount(leaderComms);
                    orderprofitdetail.setPlatAmount(platComms);
                    orderprofitdetail.setMerchantId(userorder.getMerchantId());
                    orderprofitdetail.setMerAmount(merchantComms);
                    orderprofitdetail.setServiceCharge(serviceCharge);
                    orderprofitdetailService.saveOrUpdate(orderprofitdetail);
                } else if (leaderstore.getLevel() == 2) {
                    //二级团长分佣流程
                    //1.确定二级团长的佣金
                    Double secondLeaderComms = ObjectUtil.sciCal(payAmount * (setleaderlevelService.getLeaderRate(2) * 0.01), 2);
                    //2.确定一级团长佣金
                    Double firstLeaderComms = ObjectUtil.sciCal(payAmount * (setleaderlevelService.getLeaderRate(1) * 0.01), 2);
                    //3.计算一二级团长佣金的总和
                    Double allLeaderComms = ObjectUtil.sciCal(secondLeaderComms + firstLeaderComms, 2);
                    //4.计算平台佣金
                    platComms = ObjectUtil.sciCal(payAmount - merchantComms - allLeaderComms - serviceCharge, 2);
                    //5.添加二级团长佣金信息
                    leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() + secondLeaderComms);
                    leaderprofit.setFrozen(leaderprofit.getFrozen() + secondLeaderComms);
                    leaderprofit.setGmtModify(new Date());
                    leaderprofitService.saveOrUpdate(leaderprofit);
                    //添加二级团长佣金流水
                    leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 0,
                            secondLeaderComms, "佣金收入", userorder.getOrderNo()));
                    //6.添加一级团长佣金信息
                    prams = new HashMap<String, Object>();
                    prams.put(Common.DELSTATUS, DelStatus.NODEL);
                    prams.put("storeId", leaderstore.getStoreId());
                    prams.put("level", 1);
                    Leaderstore topLeaderstore = leaderstoreService.getByParam(prams);
                    if (topLeaderstore != null) {
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put(Common.ID, topLeaderstore.getLeaderId());
                        Groupleader firstGroupleader = groupleaderService.getByParam(prams);
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("leaderId", topLeaderstore.getLeaderId());
                        Leaderprofit topleaderprofit = leaderprofitService.getByParam(prams);
                        if (topleaderprofit == null) {
                            topleaderprofit = new Leaderprofit(topLeaderstore.getLeaderId());
                            leaderprofitService.saveOrUpdate(topleaderprofit);
                        }
                        //添加顶级团长佣金信息
                        topleaderprofit.setTotalAmount(topleaderprofit.getTotalAmount() + firstLeaderComms);
                        topleaderprofit.setFrozen(topleaderprofit.getFrozen() + firstLeaderComms);
                        topleaderprofit.setGmtModify(new Date());
                        leaderprofitService.saveOrUpdate(topleaderprofit);
                        //添加顶级团长佣金流水
                        leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(topLeaderstore.getLeaderId(), 0, firstLeaderComms, "佣金收入", userorder.getOrderNo()));
                        //添加分佣记录
                        orderprofitdetail = new Orderprofitdetail(1, userorder.getOrderNo(), userorder.getPayableAmount());
                        orderprofitdetail.setLeaderId1(topLeaderstore.getLeaderId());
                        if (groupleader != null) {
                            orderprofitdetail.setFirstUser(firstGroupleader.getName());
                        }
                        orderprofitdetail.setFirstAmount(firstLeaderComms);
                        orderprofitdetail.setLeaderId2(leaderstore.getLeaderId());
                        orderprofitdetail.setSecondUser(groupleader.getName());
                        orderprofitdetail.setSecondAmount(secondLeaderComms);
                        orderprofitdetail.setPlatAmount(platComms);
                        orderprofitdetail.setMerchantId(userorder.getMerchantId());
                        orderprofitdetail.setMerAmount(merchantComms);
                        orderprofitdetail.setServiceCharge(serviceCharge);
                        orderprofitdetailService.saveOrUpdate(orderprofitdetail);
                    }
                }
            }
        }
    }

    /**
     * 判断佣金退回执行是否成功
     *
     * @param userorder
     * @return
     */
    private Integer getLeaderprofitBack(Userorder userorder) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", userorder.getOrderNo());
        Orderprofitdetail orderprofitdetail = orderprofitdetailService.getByParam(prams);
        if (orderprofitdetail != null) {
            User user = userService.get(userorder.getUserId());
            if (user != null) {
                prams = new HashMap<String, Object>();
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put(Common.USERID, user.getId());
                Userwechat userwechat = userwechatService.getByParam(prams);
                if (userwechat != null) {
                    Integer identity = checkUserIidentity(userorder.getUserId());
                    if (identity == 1) {
                        getLeaderprofitBackToUser(userwechat, userorder, orderprofitdetail);
                        return 1;
                    } else if (identity == 2) {
                        getBackLeaderprofitToUser(userorder, orderprofitdetail);
                        return 1;
                    } else if (identity == 0) {
                        return 1;
                    }
                }
            }
        }
        return 0;
    }

    /**
     * 当用户为粉丝时退回佣金信息
     *
     * @param userwechat
     * @param userorder
     * @param orderprofitdetail
     */
    private void getLeaderprofitBackToUser(Userwechat userwechat, Userorder userorder, Orderprofitdetail orderprofitdetail) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("unionid", userwechat.getUnionid());
        Leaderfan leaderfan = leaderfanService.getByParam(prams);
        if (leaderfan != null) {
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put(Common.ID, leaderfan.getLeaderId());
            Groupleader groupleader = groupleaderService.getByParam(prams);
            if (groupleader != null) {
                prams = new HashMap<String, Object>();
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put("leaderId", groupleader.getId());
                Map<String, Object> sortParams = new HashMap<String, Object>();
                sortParams.put(Common.ID, Common.DESC);
                Leaderstore leaderstore = leaderstoreService.getByParam(prams, null, sortParams);
                if (leaderstore != null) {
                    if (leaderstore.getLevel() == 1) {
                        //订单为一级团长订单时
                        //查询团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("leaderId", leaderstore.getLeaderId());
                        Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
                        if (leaderprofit != null) {
                            //添加团长佣金信息
                            leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() - orderprofitdetail.getFirstAmount());
                            leaderprofit.setFrozen(leaderprofit.getFrozen() - orderprofitdetail.getFirstAmount());
                            leaderprofit.setGmtModify(new Date());
                            leaderprofitService.saveOrUpdate(leaderprofit);
                            //添加团长佣金流水
                            leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(groupleader.getId(), 2, -orderprofitdetail.getFirstAmount(), "退款支出", userorder.getOrderNo()));
                        }
                    } else if (leaderstore.getLevel() == 2) {
                        //当团长为二级团长时
                        //5.退回二级团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("leaderId", leaderstore.getLeaderId());
                        Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
                        if (leaderprofit != null) {
                            leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() - orderprofitdetail.getSecondAmount());
                            leaderprofit.setFrozen(leaderprofit.getFrozen() - orderprofitdetail.getSecondAmount());
                            leaderprofit.setGmtModify(new Date());
                            leaderprofitService.saveOrUpdate(leaderprofit);
                            //添加二级团长佣金流水
                            leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 2,
                                    -orderprofitdetail.getSecondAmount(), "退款支出", userorder.getOrderNo()));
                        }
                        //6.退回一级团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("storeId", leaderstore.getStoreId());
                        prams.put("level", 1);
                        Leaderstore topLeaderstore = leaderstoreService.getByParam(prams);
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put(Common.ID, topLeaderstore.getLeaderId());
                        Groupleader firstGroupleader = groupleaderService.getByParam(prams);
                        if (firstGroupleader != null) {
                            prams = new HashMap<String, Object>();
                            prams.put(Common.DELSTATUS, DelStatus.NODEL);
                            prams.put("leaderId", topLeaderstore.getLeaderId());
                            Leaderprofit topleaderprofit = leaderprofitService.getByParam(prams);
                            if (topleaderprofit != null) {
                                topleaderprofit.setTotalAmount(topleaderprofit.getTotalAmount() - orderprofitdetail.getFirstAmount());
                                topleaderprofit.setFrozen(topleaderprofit.getFrozen() - orderprofitdetail.getFirstAmount());
                                topleaderprofit.setGmtModify(new Date());
                                leaderprofitService.saveOrUpdate(topleaderprofit);
                                //添加顶级团长佣金流水
                                leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(topLeaderstore.getLeaderId(), 2, -orderprofitdetail.getFirstAmount(), "退款支出", userorder.getOrderNo()));
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 当订单用户身份是团长的时候
     *
     * @param userorder
     * @param orderprofitdetail
     */
    private void getBackLeaderprofitToUser(Userorder userorder, Orderprofitdetail orderprofitdetail) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.USERID, userorder.getUserId());
        Groupleader groupleader = groupleaderService.getByParam(prams);
        //查询下单人团长信息
        if (groupleader != null) {
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("leaderId", groupleader.getId());
            Map<String, Object> sortParams = new HashMap<String, Object>();
            sortParams.put(Common.ID, Common.DESC);
            Leaderstore leaderstore = leaderstoreService.getByParam(prams, null, sortParams);
            if (leaderstore != null) {
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put("leaderId", leaderstore.getLeaderId());
                Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
                if (leaderprofit != null) {
                    if (leaderstore.getLevel() == 1) {
                        //订单为一级团长订单时
                        //添加团长佣金信息
                        leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() - orderprofitdetail.getFirstAmount());
                        leaderprofit.setFrozen(leaderprofit.getFrozen() - orderprofitdetail.getFirstAmount());
                        leaderprofit.setGmtModify(new Date());
                        leaderprofitService.saveOrUpdate(leaderprofit);
                        //添加团长佣金流水
                        leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 2, -orderprofitdetail.getFirstAmount(), "佣金退回", userorder.getOrderNo()));
                    } else if (leaderstore.getLevel() == 2) {
                        leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() - orderprofitdetail.getSecondAmount());
                        leaderprofit.setFrozen(leaderprofit.getFrozen() - orderprofitdetail.getSecondAmount());
                        leaderprofit.setGmtModify(new Date());
                        leaderprofitService.saveOrUpdate(leaderprofit);
                        //添加二级团长佣金流水
                        leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 2, -orderprofitdetail.getSecondAmount(), "佣金退回", userorder.getOrderNo()));
                        //6.添加一级团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("storeId", leaderstore.getStoreId());
                        prams.put("level", 1);
                        Leaderstore topLeaderstore = leaderstoreService.getByParam(prams);
                        if (topLeaderstore != null) {
                            prams = new HashMap<String, Object>();
                            prams.put(Common.DELSTATUS, DelStatus.NODEL);
                            prams.put("leaderId", topLeaderstore.getLeaderId());
                            Leaderprofit topleaderprofit = leaderprofitService.getByParam(prams);
                            if (topleaderprofit != null) {
                                //添加顶级团长佣金信息
                                topleaderprofit.setTotalAmount(topleaderprofit.getTotalAmount() - orderprofitdetail.getFirstAmount());
                                topleaderprofit.setFrozen(topleaderprofit.getFrozen() - orderprofitdetail.getFirstAmount());
                                topleaderprofit.setGmtModify(new Date());
                                leaderprofitService.saveOrUpdate(topleaderprofit);
                                //添加顶级团长佣金流水
                                leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(topLeaderstore.getLeaderId(), 2, -orderprofitdetail.getFirstAmount(), "佣金退款", userorder.getOrderNo()));
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 定时器线程池
     */
    private static ScheduledThreadPoolExecutor executor;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (lock == null) {
            lock = new byte[0];
            executor = new ScheduledThreadPoolExecutor(1);
        }
    }

}